package com.vshop.timingtask;


import com.vshop.service.task.ServicePlanTaskServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/***
 * 之后改成每个月的15号去执行将上个月的数据转移的操作；
 * mysql语句：
 * INSERT INTO service_plan_order_record_hist_t
 * SELECT * FROM service_plan_order_record_t as t
 * WHERE
 * DATE_FORMAT(createDate,'%Y-%m')
 * <=
 * DATE_FORMAT(date_sub(curdate(), interval 1 month),'%Y-%m')
 * AND  NOT EXISTS
 * (SELECT * FROM service_plan_order_record_hist_t as hi
 * WHERE t.orderNo=hi.orderNo )
 * ORDER BY createDate ASC;
 * <p>
 * SELECT * from
 * service_plan_order_record_hist_t
 * ORDER BY createDate asc;
 * <p>
 * 操作执行完成之后将service_plan_order_record_t表中上个月之前的空单删掉:
 * SQL语句操作：
 * DELETE FROM service_plan_order_record_t
 * WHERE
 * (payRst IS NULL OR payRst ='')
 * AND
 * DATE_FORMAT(createDate,'%Y-%m')
 * <=
 * DATE_FORMAT(date_sub(curdate(), interval 1 month),'%Y-%m') ;
 *
 * @author lm
 * @date 2018/09/9
 */

@Configuration
@EnableScheduling
@RestController
@Slf4j
public class OrderTableProcessingTask {
    @Value("${system.autoTask}")
    private boolean autoTask;
    @Autowired
    ServicePlanTaskServiceImpl taskService;

    /**
     * 定时任务做两件事情：
     * 1，每个月的15号去执行将包含上个月和之前的数据（service_plan_order_record_t）转移到（service_plan_order_record_hist_t）的操作
     * 2，转移执行完成之后将service_plan_order_record_t表中包含上个月和之前的空单删掉
     *
     * @Scheduled(cron = "0 2 5 15 * ?")
     * 具体的执行时间是：每个月15号的早上5点过2分的时候
     * @author lm
     * @date 2020/10/28 14:14
     */
    @Scheduled(cron = "0 2 5 15 * ?")
    @GetMapping(value = "orderTableProcessingTask")
    @Async
    public void execute() {
        if (autoTask) {
            task();
        }
    }

    public void task() {
        log.info("每个月15日的早上5点过2分执行任务开始执行！");

        // 1，每个月的15号去执行将包含上个月和之前的数据（service_plan_order_record_t）转移到（service_plan_order_record_hist_t）的操作
        Integer transferCount = taskService.oldDataTransfer();
        log.info(new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "操作:转移旧数据：" + transferCount + "条");

        // 2，转移执行完成之后将service_plan_order_record_t表中包含上个月和之前的空单删掉
        if (transferCount > 0) {
            //转移数据操作成功才可以做删除操作
            Integer deleteEmptyCount = taskService.oldEmptyDataDelete();
            log.info(new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "操作:删除旧空单数据：" + deleteEmptyCount + "条");
        }
        log.info("每个月15日的早上5点过2分执行任务执行完毕！");
    }
}
